package yhao.infra.web.interceptor.logger.support;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import yhao.infra.apilist.ValidationForm;
import yhao.infra.web.interceptor.logger.context.RequestContext;
import yhao.infra.web.interceptor.logger.context.RequestContextHolder;

/**
 * 请求输入参数日志记录拦截器
 * @author yoara
 */
@Aspect
@Component
public class WebAccessFormLoggerAop {
	@Around(value = "@annotation(rm)")
	public Object logger(ProceedingJoinPoint joinPoint, RequestMapping rm) throws Throwable {
		return doLogger(joinPoint);
	}

	@Around(value = "@annotation(gm)")
	public Object loggerGet(ProceedingJoinPoint joinPoint, GetMapping gm) throws Throwable {
		return doLogger(joinPoint);
	}

	@Around(value = "@annotation(pm)")
	public Object loggerPost(ProceedingJoinPoint joinPoint, PostMapping pm) throws Throwable {
		return doLogger(joinPoint);
	}

	private Object doLogger(ProceedingJoinPoint joinPoint) throws Throwable {
		RequestContext rc = RequestContextHolder.getDigestContext();
		if(rc==null){
			return joinPoint.proceed();
		}
		Object[] args = joinPoint.getArgs();
		if(args==null||args.length==0){
			return joinPoint.proceed();
		}
		for(Object arg:args) {
			if (!(arg instanceof ValidationForm)) {
				continue;
			}
			rc.setForm((ValidationForm)arg);
			break;
		}
		return joinPoint.proceed();
	}

	/**@Around(value = "@annotation(hc)")
	public Object formSynch(ProceedingJoinPoint joinPoint, HystrixCommand hc) throws Throwable {
		Object[] args = joinPoint.getArgs();
		if(args==null||args.length==0 || args.length>1 ||
				RequestContextHolder.getDigestContext()==null ||
				RequestContextHolder.getDigestContext().getForm()==null){
			return joinPoint.proceed();
		}
		Object result = null;
		try{
			result = joinPoint.proceed();
		}finally {
			if(result!=null && result.getClass().equals(args[0].getClass())){
				for(Object arg:args){
					if(result.getClass().equals(arg.getClass())){
						BeanUtils.copyProperties(result,arg);
						break;
					}
				}
			}
		}
		return result;
	}**/
}